﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook.Web;
using WhsFacebook.Net.Web.Database;

namespace WhsFacebook.Net.Web.Facebook
{
    public partial class InviteFriends : CanvasFBMLBasePage
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(InviteFriends));

        public InviteFriends()
        {
            this.RequireLogin = true;
        }

        protected void Page_Load(object sender, EventArgs ee)
        {
            // form posted?
            var doInvite = FacebookConverter.ToBoolean(this.Request.Params["doInvite"]);
            
            if (doInvite)
            {
                // prepare
                var defMaster = (DefaultMaster)this.Master;
                var userId = defMaster.FacebookVisit.UserId;
                var whsId = defMaster.FacebookVisit.WhsInstanceId;
                var selectedFriendsList = FacebookConverter.ToString(this.Request.Params["ids[]"]);

                if (!string.IsNullOrEmpty(selectedFriendsList))
                {
                    this.friendsInvited.Visible = true;

                    // get selected friends
                    var selectedFriends = selectedFriendsList.Split(',').Select(FacebookConverter.ToInt64);

                    // log this action
                    try
                    {
                        using (var e = new WhsFacebookEntities())
                        {
                            var ua = new DbUserInviteLog()
                            {
                                FacebookUserId = userId,
                                IsLoggedIn = defMaster.FacebookVisit.IsLoggedIn,
                                Occurrence = defMaster.FacebookVisit.TimeStamp,
                                ViaFacebookUserId = defMaster.FacebookVisit.ViaUserId,
                                WhsInstanceId = defMaster.FacebookVisit.WhsInstanceId,
                            };

                            foreach (var friend in selectedFriends)
                            {
                                ua.Friends.Add(new DbUserActionLogFriend()
                                {
                                    FacebookUserId = userId,
                                    FriendUserId = friend,
                                });
                            }

                            e.AddToUserActionsLog(ua);
                            e.SaveChanges();
                        }
                    }
                    catch (Exception x)
                    {
                        if (_log.IsWarnEnabled)
                            _log.Warn("Failed to log Facebook invite", x);
                    }
                }
                else
                {
                    // redirect to default page
                    this.redirectToHome.Visible = true;
                }
            }
            else
            {
                this.selectFriends.Visible = true;

                using (var db = new Database.WhsFacebookEntities())
                {
                    // query instance id
                    var defMaster = (DefaultMaster) this.Master;
                    var userId = defMaster.FacebookVisit.UserId;
                    var friends = defMaster.FacebookVisit.FriendsUserIds;

                    var instanceId = (
                                         from t in db.FacebookInstanceMappings
                                         where t.FacebookUserId == userId
                                         select t.InstanceId
                                     ).First();

                    // query and exclude associated friends
                    var knownFriends = (
                                           from f in db.FacebookUserStorageInfos
                                           where friends.Contains(f.FacebookUserId)
                                           orderby f.StorageSize descending
                                           select f.FacebookUserId
                                       ).ToArray();

                    if (knownFriends.Length > 0)
                    {
                        this.friendSelector.ExcludeIds = string.Join(",", knownFriends);
                    }
                }
            }
        }

        public string GetInvitationContent()
        {
            var defMaster = (DefaultMaster)this.Master;
            var userId = defMaster.FacebookVisit.UserId;

            var sb = new StringBuilder();

            sb.Append("<fb:name uid=\"");
            sb.Append(userId);
            sb.Append("\" firstnameonly=\"true\" shownetwork=\"false\" />");
            sb.Append(" just invited you to the new <a href=\"http://apps.facebook.com/windowshomeserver\">Windows Home Server on Facebook</a> application!");
            sb.AppendLine();
            sb.AppendLine();
            sb.Append("<fb:req-choice url=\"http://apps.facebook.com/windowshomeserver\" label=\"Visit\"/>");

            return sb.ToString();
        }
    }
}